package com.CST.controller;

import cn.hutool.crypto.SecureUtil;
import com.CST.annotation.ResultObjectAnnotation;
import com.CST.common.api.Response;
import com.CST.common.api.ResultObject;
import com.CST.common.constant.DmlTypeConstant;
import com.CST.common.constant.HttpConstant;
import com.CST.dto.PassWordDTO;
import com.CST.dto.SysUserDTO;
import com.CST.entity.BdSysUser;
import com.CST.service.IBdSysUserService;
import com.CST.util.JwtTokenUtil;
import com.CST.util.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户管理
 * </p>
 * @author y
 * @since 2021-09-27
 */
@Api(tags = {"系统用户管理"})
@RestController
@RequestMapping("/bdSysUser")
@Log4j2
public class BdSysUserController {

    @Autowired
    private IBdSysUserService iBdSysUserService;


    /**
     * <p>pc登录</p >
     * @param bdSysUser
     * @author y
     * @since 2021/09/27 09:31
     * @return java.lang.Object
     */
    @PostMapping("/pcLogin")
    @ApiOperation("pc登录")
    public Object pcLogin(@RequestBody BdSysUser bdSysUser) {
        final String userName = bdSysUser.getUserName();
        final String userPassword = SecureUtil.md5(bdSysUser.getUserPassword());
        final Map<String, Object> count = iBdSysUserService.getMap(new LambdaQueryWrapper<>(new BdSysUser())
                .eq(BdSysUser::getUserName, userName)
                .eq(BdSysUser::getUserPassword, userPassword));
        //登录成功，获取token
        if (count != null && !count.isEmpty()) {
            final String token = JwtTokenUtil.generateToken(count);
            //final String roleCode = Objects.toString(count.get("ROLE_CODE"));
            final String realName = Objects.toString(count.get("REAL_NAME"));
            Map<String, String> map = new HashMap<>();
            map.put(HttpConstant.TOKEN, token);
            log.info("登陆token--" + token);
            //map.put("role", roleCode);
            map.put("userName", userName);
            map.put("realName", realName);
            map.put("id", Objects.toString(count.get("ID")));
            System.setProperty("userName",userName);
            return ResultObject.success(map);
        }
        return ResultObject.failed("账号密码错误！");
    }

    /**
     * <p>新增用户</p >
     * @param bdSysUser
     * @author y
     * @since 2021/09/27 09:32
     * @return com.CST.common.api.Response
     */
    @ApiOperation("新增用户")
    @PostMapping("/insertSysUserManager")
    public Response insertSysUser(@RequestBody BdSysUser bdSysUser) {
        return iBdSysUserService.insertSysUser(bdSysUser);
    }

    /**
     * <p>根据用户名或真实姓名查询</p >
     * @author y
     * @since 2021/09/27 09:13
     * @return com.CST.entity.BdSysRole
     */
    @ApiOperation("根据用户名或真实姓名查询")
    @GetMapping("/getUsers")
    public ResultObject getUsers(@RequestParam("realName") String realName, @RequestParam("userName") String userName) {
        return ResultObject.successReturn(iBdSysUserService.getUsers(realName, userName));
    }

    /**
     * <p>修改密码</p >
     * @param passWordDto
     * @author y
     * @since 2021/09/27 09:32
     * @return java.lang.Object
     */
    @PostMapping("/changePassword")
    @ApiOperation("修改密码")
    public ResultObject changePassword(@RequestBody PassWordDTO passWordDto) {
        return iBdSysUserService.updateUserPassword(passWordDto);
    }

    @PostMapping("/reStartPassword")
    @ApiOperation("初始密码")
    public ResultObject reStartPassword(@RequestParam String id) {
        return iBdSysUserService.reStartPassword(id);
    }

    /**
     * <p>列表查询</p >
     * @param sysUserDto
     * @author y
     * @since 2021/09/27 09:32
     * @return java.lang.Object
     */
    @PostMapping("/getSysUserList")
    @ApiOperation("列表查询")
    public ResultObject getSysUserList(@RequestBody SysUserDTO sysUserDto) {
        return ResultObject.successReturn(iBdSysUserService.getSysUserList(sysUserDto));
    }

//    /**
//     * <p>查询用户权限</p >
//     * @param userName
//     * @author y
//     * @since 2021/10/11 16:18
//     * @return java.util.List<com.CST.entity.BdSysUser>
//     */
//    @PostMapping("/getMenuByUserName")
//    @ApiOperation("查询用户权限")
//    public ResultObject getMenuByUserName(@RequestParam("userName") String userName) {
//        return ResultObject.successReturn(iBdSysUserService.getMenuByUserName(userName));
//    }

    @PostMapping("/updateSysUser")
    @ApiOperation("编辑用户")
    @ResultObjectAnnotation(value= DmlTypeConstant.INSERT,successMessage = "编辑成功!",errorMessage = "编辑失败!")
    public Object updateSysUser(@RequestBody BdSysUser  bdSysUser) {

        //密码加密
        if (null != bdSysUser.getUserPassword() && !"".equals(bdSysUser.getUserPassword())){
            bdSysUser.setUserPassword(MD5.crypt(bdSysUser.getUserPassword()));}
        //判断是否已存在
        List<BdSysUser> sysRoleExist= iBdSysUserService.getUser(bdSysUser.getUserName());
        List<BdSysUser> collect = sysRoleExist.stream().filter(e -> !e.getId().equals(bdSysUser.getId()))
                .collect(Collectors.toList());
        //已存在此角色名
        if (!CollectionUtils.isEmpty(collect)) {
            return new Response(500, "角色名称已存在");
        }
        //修改用户基本信息
        int updateSysUser = iBdSysUserService.updateSysUser(bdSysUser);
        if (updateSysUser < 1) {
            return new Response(500, "修改失败");
        } return new Response("修改成功");
    }

    @GetMapping("/getById/{id}")
    @ApiOperation("查看")
    @ResultObjectAnnotation(DmlTypeConstant.SELECT)
    public Object getById(@PathVariable String id) {
        return iBdSysUserService.getById(id);
    }

    @DeleteMapping("/delete/{ids}")
    @ApiOperation("删除")
    @ResultObjectAnnotation(DmlTypeConstant.DELETE)
    public Object delete(@PathVariable List<String> ids) {
        return iBdSysUserService.removeByIds(ids);
    }


}
